using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace eGov.SharePoint.MyPeeps.WebParts
{
    [Guid("43849b8a-a716-4fef-949b-bb352a9405b7")]
    public class WelcomeMessage : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        private string _myProperty = null;


        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        {
            get
            {
                if (_myProperty == null)
                {
                    _myProperty = "Hello SharePoint";
                }
                return _myProperty;
            }
            set { _myProperty = value; }
        }


        public WelcomeMessage()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();

                    // Your code here...
                    this.Controls.Add(new LiteralControl(this.MyProperty));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    // Your code here...
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (this.Context.User.Identity.IsAuthenticated)
            {
                writer.Write("<div class=\"description\">&nbsp;&nbsp;Hello,&nbsp;<span id=\"UserName\">" + GetUserName() + "!</span>&nbsp;&nbsp;<br><br>&nbsp;&nbsp;Click on 'Visitors' for Bing Maps.&nbsp;&nbsp;</div>");
            }
            else
            {
                writer.Write("<div class=\"description\">&nbsp;&nbsp;Windows Live Authentication is now&nbsp;&nbsp;<br>&nbsp;&nbsp;supported!<br><br>&nbsp;&nbsp;Please sign in for additional features!&nbsp;&nbsp;</div>");
            }
        }

        string GetUserName()
        {
            string userName = string.Empty;
            if (Context.User.Identity.AuthenticationType == "Forms")
            {
                SPContext context = SPContext.Current;

                try
                {
                    SPWeb web = SPContext.Current.Web;
                    {
                        SPList idList = web.Lists["LiveIDProfiles"];
                        foreach (SPListItem item in idList.Items)
                        {
                            if (item["UUID"].ToString() == Context.User.Identity.Name)
                            {
                                userName = item["DisplayName"].ToString();
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    userName = Context.User.Identity.Name;
                }
            }
            else
            {
                userName = Context.User.Identity.Name;
            }
            return userName;
        }

    }
}
